package com.lxc.lib.net.http

import com.lxc.lib.net.storage.BaseResponse
import kotlinx.coroutines.*
import retrofit2.Response
import java.lang.Exception

/**
 *@author: xuancai.Liu
 *@create: 2021-09-06 16:35
 *@program: NetDemo
 *@description:
 */
class HttpManager private constructor(
    private val externalScope: CoroutineScope,
    private val defaultDispatcher: CoroutineDispatcher,
    private val start: CoroutineStart,
) {

    fun <T> goJson(requestService: Deferred<Response<T>>, listener: (BaseResponse<T>) -> Unit) {
        externalScope.launch(defaultDispatcher, start) {
            try {
                ensureActive()
                val response = requestService.await()
                ensureActive()
                formatResponse(response, listener)
            } catch (e: Exception) {
                ensureActive()
                listener.invoke(BaseResponse.failure())
            }
        }.start()
    }

    companion object {
        fun <T> formatResponse(response: Response<T>, listener: (BaseResponse<T>) -> Unit) {
            try {
                listener.invoke(RequestHelper.requestData(response))
            } catch (e: Exception) {
                listener.invoke(BaseResponse.failure())
            }
        }
    }

    class Builder(
        private val externalScope: CoroutineScope,
        private val defaultDispatcher: CoroutineDispatcher = Dispatchers.IO,
        private val start: CoroutineStart = CoroutineStart.LAZY,
    ) {
        fun build(): HttpManager {
            return HttpManager(externalScope, defaultDispatcher, start)
        }
    }

}

